package quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import static org.quartz.CronScheduleBuilder.cronSchedule;

public class HelloQuartzScheduling {

    public static void main(String[] args) throws SchedulerException {

        //创建一个scheduler
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.getContext().put("sk0", 0);
        scheduler.getContext().put("skey", "svalue");

        //创建一个Trigger
        TriggerKey triggerKey1 = new TriggerKey("helloQuartzTrigger", "helloTriggerGroup");
        SimpleScheduleBuilder scheduleBuilder1 = SimpleScheduleBuilder
                .simpleSchedule().withIntervalInSeconds(3).repeatForever();
        Trigger trigger1 = TriggerBuilder.newTrigger()
                .withIdentity(triggerKey1)
                .usingJobData("tk0", 0)
                .usingJobData("tk1", "tv1")
//                .withSchedule(scheduleBuilder1)
                .withSchedule(cronSchedule("0/3 6 * * * ?"))
                .build();
        trigger1.getJobDataMap().put("tk2", "tv2");
        trigger1.getJobDataMap().put("k", "tv");

        //创建一个job
        JobKey jobKey1 = new JobKey("helloQuartzJob-1", "helloJobGroup-1");
        JobDetail jobDetail1 = JobBuilder
                .newJob(HelloQuartzJob.class)
                .withIdentity(jobKey1)
                .storeDurably()
                .usingJobData("jk0", 1)
                .usingJobData("jk1", "jv1")
                .build();
        jobDetail1.getJobDataMap().put("jk2", "jv2");
        jobDetail1.getJobDataMap().put("k", "jv");

        //注册trigger并启动scheduler
//        scheduler.scheduleJob(jobDetail1, trigger1);
//        scheduler.start();

        JobDetail jobDetail2 = JobBuilder
                .newJob(HelloQuartzJob.class)
                .withIdentity("helloQuartzJob-2", "helloJobGroup-2")
                .usingJobData("jk0", 2)
                .build();

        TriggerKey triggerKey2 = new TriggerKey("helloQuartzTrigger2", "helloTriggerGroup");
        SimpleScheduleBuilder scheduleBuilder2 = SimpleScheduleBuilder
                .simpleSchedule().withIntervalInSeconds(3).repeatForever();
        Trigger trigger2 = TriggerBuilder.newTrigger()
                .withIdentity(triggerKey2)
//                .withSchedule(scheduleBuilder2)
                .withSchedule(cronSchedule("0/3 6 * * * ?"))
                .build();
        Map<JobDetail, Set<? extends Trigger>> triggersAndJobs = new HashMap(){{
            put(jobDetail1, new HashSet<Trigger>(){{add(trigger1);}});
            put(jobDetail2, new HashSet<Trigger>(){{add(trigger2);}});
        }};
        scheduler.scheduleJobs(triggersAndJobs, false);
        scheduler.start();

    }

}
